package com.example.demo.core.exception;

import com.example.demo.core.api.ResultCode;
import com.example.demo.core.api.ResultVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import reactor.core.publisher.Mono;

/**
 * @author T0220165
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    public Mono<ResultVo> handleHttpMediaTypeNotAcceptableException(HttpMediaTypeNotAcceptableException e) {
        log.error("HttpMediaTypeNotAcceptableException: {}", e.getMessage());
        return Mono.just(new ResultVo(ResultCode.NOT_ACCEPTABLE));
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Mono<ResultVo> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("HttpMessageNotReadableException: {}", e.getMessage());
        String message = e.getCause() != null ? e.getCause().getMessage() : "参数解析失败";
        return Mono.just(new ResultVo(ResultCode.PARAM_ERROR, message));
    }

    @ExceptionHandler(BindException.class)
    public Mono<ResultVo> handleHttpMediaTypeNotAcceptableException(BindException e) {
        log.error("BindException: {}", e.getMessage());
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        return Mono.just(new ResultVo(ResultCode.PARAM_ERROR, error.getDefaultMessage()));
    }


    @ExceptionHandler(ApiException.class)
    public Mono<ResultVo> handleApiException(ApiException e) {
        log.error("ApiException: {}", e.getMessage());
        return Mono.just(new ResultVo(e.getCode(), e.getMsg(), e.getMessage()));
    }
}
